package server

import (
	"fmt"
	"proxy_resource_test/bootstrap/models"
	"proxy_resource_test/dao"
	"proxy_resource_test/utils/logging"
)

// DealIpPool 处理ip池
func DealIpPool(data []models.IpInfo) error {
	if len(data) == 0 {
		return nil
	}
	// 1. 按 Operator 分组
	newData := make(map[string][]models.IpInfo, len(data))
	for _, v := range data {
		newData[v.Operator] = append(newData[v.Operator], v)
	}

	// 2. 获取基础表名
	var info models.IpInfo
	baseTable := info.TableName()

	// 3. 针对每个分组，批量入库
	for op, batch := range newData {
		tableName := fmt.Sprintf("%s_%s", baseTable, op)
		if err := dao.GetCkDB().
			Table(tableName).
			CreateInBatches(batch, len(batch)).
			Error; err != nil {
			logging.Error("DealIpPool: insert into %s failed: %v", tableName, err)
			return err
		}
	}

	return nil
}

// AutoMigrateInfo 建表
func AutoMigrateInfo(sc string) {
	var info models.IpInfo
	tableName := fmt.Sprintf("%s_%s", info.TableName(), sc)
	if !dao.GetCkDB().Migrator().HasTable(tableName) {
		if err := dao.GetCkDB().Table(tableName).AutoMigrate(&models.IpInfo{}); err != nil {
			logging.Error(fmt.Sprintf("AutoMigrateInfo error: %v", err))
		}
	}
}
